package com.gitee.fastmybatis.spring.boot.autoconfigure.multi;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;

public class HikariDataSourceCreator implements DataSourceCreator {

    @Override
    public DataSource create(DataSourceProp dataSourceProp) {
        long connectionTimeout = dataSourceProp.getConnectionTimeout();
        long validationTimeout = dataSourceProp.getValidationTimeout();
        int maxPoolSize = dataSourceProp.getMaxPoolSize();
        int minIdle = dataSourceProp.getMinIdle();

        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(dataSourceProp.getDriverClassName());
        hikariConfig.setJdbcUrl(dataSourceProp.getUrl());
        hikariConfig.setUsername(dataSourceProp.getUsername());
        hikariConfig.setPassword(dataSourceProp.getPassword());
        if (connectionTimeout > 0) {
            hikariConfig.setConnectionTimeout(connectionTimeout);
        }
        if (validationTimeout > 0) {
            hikariConfig.setValidationTimeout(validationTimeout);
        }
        long idleTimeout = dataSourceProp.getIdleTimeout();
        if (idleTimeout > 0) {
            hikariConfig.setIdleTimeout(idleTimeout);
        }
        long leakDetectionThreshold = dataSourceProp.getLeakDetectionThreshold();
        if (leakDetectionThreshold > 0) {
            hikariConfig.setLeakDetectionThreshold(leakDetectionThreshold);
        }
        long maxLifetime = dataSourceProp.getMaxLifetime();
        if (maxLifetime > 0) {
            hikariConfig.setMaxLifetime(maxLifetime);
        }
        if (maxPoolSize > 0) {
            hikariConfig.setMaximumPoolSize(maxPoolSize);
        }
        if (minIdle > 0) {
            hikariConfig.setMinimumIdle(minIdle);
        }
        return new HikariDataSource(hikariConfig);
    }
}
